using System;
using System.Web;
using NHibernate;

namespace Domain
{
    internal class NHibernateHttpModule : IHttpModule
    {
        private const string ContextItemsKey = "NHibernateSession";
        
        public void Init(HttpApplication application)
        {
            application.EndRequest += HandleEndRequest;
        }

        public void HandleEndRequest(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            HttpContext context = application.Context;

            ISession session = context.Items[ContextItemsKey] as ISession;
            if (session != null && session.IsOpen)
            {
                session.Flush();
                session.Close();
            }

            context.Items[ContextItemsKey] = null;
        }

        public static ISession CurrentSession
        {
            get
            {
                HttpContext currentContext = HttpContext.Current;
                ISession session = currentContext.Items[ContextItemsKey] as ISession;

                if (session == null)
                {
                    session = NHibernateHelper.Instance.OpenSession();
                    currentContext.Items[ContextItemsKey] = session;
                }

                return session;
            }
        }

        public void Dispose()
        {
            // Nothing
        }
    }
}
